using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;

namespace Core.SimpleTemp.Api.Api
{
    /// <summary>
    /// ZB_SafetyTrainer
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]//验证是否登录
    public class ZB_SafetyTrainerController : CoreApiController
    {
        private readonly ZB_SafetyTrainerService _service;
        private readonly CBS_TotalCheckItemService _serviceItem;
        /// <summary>
        /// ZB_SafetyTrainer
        ///</summary>
        public ZB_SafetyTrainerController(ZB_SafetyTrainerService service, CBS_TotalCheckItemService serviceItem)
        {
            _service = service;
            _serviceItem = serviceItem;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(ZB_SafetyTrainerController) + "_" + nameof(ZB_SafetyTrainerController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetList(PagingModel<ZB_SafetyTrainerDto>
                pagingQueryModel)
        {
            IPageModel<ZB_SafetyTrainerDto>
                result;
            result = await _service.GetList(pagingQueryModel);
            for (int i = 0; i < result.PageData.Count; i++)
            {
                
                if (pagingQueryModel.Model.TrainTimeStart == null) { }
                else
                {
                    result.PageData[i].ZB_SafetyTrainerDetail = result.PageData[i].ZB_SafetyTrainerDetail.Where(x => Convert.ToDateTime(x.trainTime) >= pagingQueryModel.Model.TrainTimeStart).ToList();// + " 00:00:00.000"
                }

                if (pagingQueryModel.Model.TrainTimeEnd == null) { }
                else
                {
                    result.PageData[i].ZB_SafetyTrainerDetail = result.PageData[i].ZB_SafetyTrainerDetail.Where(x => Convert.ToDateTime(x.trainTime) <= pagingQueryModel.Model.TrainTimeEnd).ToList();
                }

                //if (result.PageData[i].SysDataDic.Key == "0")
                //{
                //    result.PageData[i].Mark01 = "3";
                    
                //}
                //else
                //{
                //    result.PageData[i].Mark01 = "5";
                //}
                //培训内容
                if (pagingQueryModel.Model.trainMain == null) { }
                else
                {
                    result.PageData[i].ZB_SafetyTrainerDetail = result.PageData[i].ZB_SafetyTrainerDetail.Where(x => x.trainMain.Contains(pagingQueryModel.Model.trainMain)).ToList();
                }

                if (pagingQueryModel.Model.CreateTime == null)
                {
                    result.PageData[i].ZB_SafetyTrainerDetail = result.PageData[i].ZB_SafetyTrainerDetail.Where(x => !x.IsDeleted).ToList();
                    result.PageData[i].qualifiedTrainNumber = result.PageData[i].ZB_SafetyTrainerDetail.Where(x => !x.IsDeleted && x.IsQualified == "合格").ToList().Count;

                }
                else
                {
                    result.PageData[i].ZB_SafetyTrainerDetail = result.PageData[i].ZB_SafetyTrainerDetail.Where(x => !x.IsDeleted && Convert.ToDateTime(x.trainTime).Year == pagingQueryModel.Model.CreateTime.Value.Year).ToList();
                    result.PageData[i].qualifiedTrainNumber = result.PageData[i].ZB_SafetyTrainerDetail.Where(x => !x.IsDeleted && x.IsQualified == "合格" && Convert.ToDateTime(x.trainTime).Year == pagingQueryModel.Model.CreateTime.Value.Year).ToList().Count;
                }

            }
            ////查询    已培训次数
            //if (pagingQueryModel.Model.trainedNumber == null) { } else
            //{
            //    result.PageData = result.PageData.Where(m => m.ZB_SafetyTrainerDetail.Count==(Convert.ToInt32(pagingQueryModel.Model.trainedNumber.Value)) && Convert.ToInt32(pagingQueryModel.Model.trainedNumber.Value) >= 0).ToList();
            //}
            //result.PageData = result.PageData.Where(m => m.ZB_SafetyTrainerDetail.Count > 0).ToList();
            //result.RowCount = result.PageData.Count;
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(ZB_SafetyTrainerController) + "_" + nameof(ZB_SafetyTrainerController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult>
            SaveAsync(ZB_SafetyTrainerDto dto)
        {
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                if (dto.NameId == null || dto.NameId == Guid.Empty)
                {
                    string SysDepartmentID = await _serviceItem.GetDepartmentId(UserIdentity.Id.ToString());
                    if (SysDepartmentID == null || SysDepartmentID == "") { }
                    else
                    {
                        dto.CreateDept = Guid.Parse(SysDepartmentID);
                    }
                    dto.CreateFactory = UserIdentity.Factory;
                    await _service.InsertAsync(dto);
                    return this.JsonSuccess(string.Empty);
                }
                else
                {
                    var name = await _serviceItem.GetNameId(dto.NameId.Value.ToString());
                    if (name == null || name == "")
                    {
                        await _service.InsertAsync(dto);
                        return this.JsonSuccess(string.Empty);
                    }
                    else
                    {
                        return this.JsonFaild("安全管理培训师已存在");
                    }
                }
                
               
            }
            else
            {
                string SysDepartmentID = await _serviceItem.GetDepartmentId(UserIdentity.Id.ToString());
                if (SysDepartmentID == null || SysDepartmentID == "") { }
                else
                {
                    dto.UpdateDept = Guid.Parse(SysDepartmentID);
                }
                await _service.UpdateAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(ZB_SafetyTrainerController) + "_" + nameof(ZB_SafetyTrainerController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult>
            DeleteMutiAsync([FromBody]Guid[] ids)
        {

            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult>
            Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            if (model == null) return this.JsonFaild("未找到对应数据:" + id);
            return this.JsonSuccess(model);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(ZB_SafetyTrainerController) + "_" + nameof(ZB_SafetyTrainerController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<ZB_SafetyTrainerDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="data"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Import")]
        [PermissionFilter(nameof(CBS_TrainRecordController) + "_" + "导入")]
        public async Task<IActionResult> ImportAsync([FromForm]String data, [FromForm]List<IFormFile> file)
        {
            var retMeg = await _service.ImportAsync(file[0], data);
            if (!retMeg.Any())
            {
                return this.JsonSuccess();
            }
            else
            {
                return this.JsonFaild(retMeg[0].ToString());
            }
        }
        #endregion


    }
}
